package com.krtech.wecard.module.mayi.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.krtech.wecard.config.WecardRedisTemplate;
import com.krtech.wecard.module.mayi.MayiPayEnums;
import com.krtech.wecard.module.mayi.entity.MayiDianzanLog;
import com.krtech.wecard.module.mayi.entity.MayiPayList;
import com.krtech.wecard.module.mayi.service.MayiDianzanLogService;
import com.krtech.wecard.module.mayi.service.MayiPayListService;
import com.krtech.wecard.module.mayi.service.impl.MayiPayListServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class DianZanRedisLoseTask {

    @Autowired
    private MayiPayListService payListService;

    @Autowired
    private WecardRedisTemplate redisTemplate;

    @Autowired
    private MayiDianzanLogService dianzanLogService;


    //todo 我不名单，为什么一个点赞任务为什么在redis中会被删除
//    @Scheduled(cron = "0/30 * * * * ? ")
//    public void liuliangTask(){
////        String urlHash = MayiPayListServiceImpl.urlHash("https://ur.alipay.com/_5OLKikOwDyIAEHlXH85QLg");
//        String urlHash = "523083b20e9a49c881c4f316f942cada";
//
//        String count = redisTemplate.get("dianzan:" + urlHash);
//        System.out.println(count);
//    }

//        @Scheduled(cron = "0/30 * * * * ? ")
    @Scheduled(cron = "0 0/5 * * * ?")
    public void liuliangTask(){
        //拿到正在执行的点赞任务
        List<MayiPayList> dianzanTaskList = payListService.list(new QueryWrapper<MayiPayList>()
                .eq(MayiPayList.COL_TYPE, MayiPayEnums.TYPE_DIANZAN)
                .in(MayiPayList.COL_STATUS, MayiPayEnums.PAY_AND_NOT_RUN, MayiPayEnums.PAY_AND_RUNING)
        );

        for (MayiPayList payList:dianzanTaskList){
            String urlHash = MayiPayListServiceImpl.urlHash(payList.getUrl());
            boolean exists = redisTemplate.exists("dianzai:set:success:" + urlHash);
            if (!exists){
                //我开始创建并添加数据
                //搜索这个已经存在的machineId数据
                List<MayiDianzanLog> dianzanLogList = dianzanLogService.list(new QueryWrapper<MayiDianzanLog>()
                        .eq(MayiDianzanLog.COL_FK_PAY_LIST_ID, payList.getId()));

                List<String> machineIdList = dianzanLogList.stream().map(MayiDianzanLog::getMachineId).collect(Collectors.toList());

                Long batchAddCount = redisTemplate.setBatchAdd("dianzai:set:success:" + urlHash, machineIdList);
                log.info("点赞任务redis恢复，id:"+payList.getId()+",urlHash:"+urlHash+"，恢复数量:"+batchAddCount);

                //todo Long decr = redisTemplate.decr("dianzan:" + urlHash);
                //说明这个值是不对的，把这个值给恢复，还需要判断上次更新时间
                //1.判断这个值是不是负数 2.判断这个paylist上次更新时间是否超过五分钟了 3.经过双重判断才开始修改
                String countStr = redisTemplate.get("dianzan:" + urlHash);
                Integer count = Integer.parseInt(countStr);

                if (StrUtil.isNotEmpty(payList.getType())
                        && payList.getType().equals(MayiPayEnums.TYPE_DIANZAN)
                        && count <= 0
                        && payList.getReachCount() < payList.getRealGoalCount()){

                    //计算偏移时间
                    if (payList.getUpdatedTime() != null){
                        DateTime now = DateUtil.date();

                        long between = DateUtil.between(payList.getUpdatedTime(), now, DateUnit.MINUTE);
                        //超时五分钟
                        if (between > 5){
                            //计算差额
                            Integer redisCount = payList.getRealGoalCount() - payList.getReachCount();

                            redisTemplate.set("dianzan:"+urlHash,redisCount.toString());
                        }
                    }
                }



            }else {
                //如果不存在，核实
                //1.判断这个值是不是负数 2.判断这个paylist上次更新时间是否超过五分钟了 3.经过双重判断才开始修改
                String countStr = redisTemplate.get("dianzan:" + urlHash);
                Integer count = Integer.parseInt(countStr);

                if (StrUtil.isNotEmpty(payList.getType())
                        && payList.getType().equals(MayiPayEnums.TYPE_DIANZAN)
                        && count <= 0
                        && payList.getReachCount() < payList.getRealGoalCount()){

                    //计算偏移时间
                    if (payList.getUpdatedTime() != null){
                        DateTime now = DateUtil.date();

                        long between = DateUtil.between(payList.getUpdatedTime(), now, DateUnit.MINUTE);
                        //超时五分钟
                        if (between > 5){
                            //计算差额
                            Integer redisCount = payList.getRealGoalCount() - payList.getReachCount();

                            redisTemplate.set("dianzan:"+urlHash,redisCount.toString());
                        }
                    }
                }
            }
        }
    }
}
